package demo1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoService {
    private final ServerSocket serverSocket;
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    public TcpEchoService(Integer port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    static void main() throws IOException {
        TcpEchoService service = new TcpEchoService(9090);
        service.start();
    }

    public void start() throws IOException {
        System.out.println("服务器开启");
        while (true) {
            //1. 建立连接
            //获取到的requestSocket对象作为后续传输的网卡
            Socket requsetSocket = serverSocket.accept();
            //为了避免处理请求就不能继续联系连接 弄个线程池来处理这些请求 好让请求能够快速建立连接 不用等待
            //2. 处理连接
            executorService.submit(() -> {
                try {
                    processRequest(requsetSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }


    }

    void processRequest(Socket requsetSocket) throws IOException {
        System.out.println("客户端信息: " + "端口号: " + requsetSocket.getPort() + "ip: " + requsetSocket.getInetAddress());
        try (InputStream inputStream = requsetSocket.getInputStream(); OutputStream outputStream = requsetSocket.getOutputStream()) {
            while (true) {
                //对输入输出流进行包装 方便后续观察
                Scanner scanner = new Scanner(inputStream);
                PrintWriter printWriter = new PrintWriter(outputStream);
                if (!scanner.hasNext()) {
                    //连接关闭
                    break;
                }
                String request = scanner.next();
                System.out.println("请求信息: " + request);
                String reponse = process(request);
                printWriter.println(reponse);
                //由于传输层使用tcp的套接字输出 输入 都有缓冲区 所以需要刷新缓冲区 不要数据是发不出去的 一直搁缓冲区待着
                printWriter.flush();
            }
        } finally {
            //关闭连接
            serverSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

}
